package com.hangwei.paperless;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.hangwei.paperless.adapter.TypeAdapter;
import com.hangwei.paperless.model.bean.DictBean;
import com.hangwei.paperless.model.bean.PicResult;
import com.hangwei.paperless.model.entity.CameraEvent;
import com.hangwei.paperless.net.NetManager;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.utils.JsonPostUtil;
import com.hangwei.paperless.widget.MaxRecyclerView;
import com.twelve.all.base.CameraActivity;
import com.twelve.all.net.CallBack;
import com.twelve.all.net.ResponseInfo;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.ToastUtil;
import com.twelve.all.utils.Tools;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observable;

/**
 * Created by 张龙臣 on 2020/12/16.
 */

public class EngTreatmentEditActivity extends CameraActivity {

    private LoadingDialog mLoadingDialog;
    private TypeAdapter mAdapter;
    private TypeAdapter mAdapter1;
    //    private RecyclerView mRecyclerViewPic;
    private LinearLayout mLlPicContainer;
    private String mBillId;
    private String mStepId;
    private String mWoNo;
    private String mPwoNo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUpLoadNow = false;
        PIC_COUNT = 8;
        setContentView(R.layout.activity_eng_treatment_edit);
        findViewById(R.id.view0).setOnClickListener(v -> finish());
        findViewById(R.id.back).setOnClickListener(v -> finish());
        MaxRecyclerView recyclerView = findViewById(R.id.recyclerView);
        MaxRecyclerView recyclerView1 = findViewById(R.id.recyclerView1);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView1.setLayoutManager(new GridLayoutManager(this, 3));
        mAdapter = new TypeAdapter(null, 0);
        recyclerView.setAdapter(mAdapter);
        mAdapter1 = new TypeAdapter(null, 1);
        recyclerView1.setAdapter(mAdapter1);
        mLoadingDialog = new LoadingDialog(this);
        initEngData(mAdapter, 0);
        initEngData(mAdapter1, 1);
        LinearLayout llConfirm = findViewById(R.id.llConfirm);
        LinearLayout llCancel = findViewById(R.id.llCancel);
        Intent intent = getIntent();
        mBillId = intent.getStringExtra("billId");
        mStepId = intent.getStringExtra("stepId");
        mWoNo = intent.getStringExtra("woNo");
        mPwoNo = intent.getStringExtra("pwoNo");
        String pn = intent.getStringExtra("pn");
        String sn = intent.getStringExtra("sn");
        String apn = intent.getStringExtra("apn");
        String description = intent.getStringExtra("description");
        EditText etDescription = findViewById(R.id.etDescription);
        EditText etPN = findViewById(R.id.etPN);
        EditText etSN = findViewById(R.id.etSN);
        EditText etAPN = findViewById(R.id.etAPN);
        EditText etDes = findViewById(R.id.etDes);
        etPN.setText(Tools.checkedString(pn));
        etSN.setText(Tools.checkedString(sn));
        etDescription.setText(Tools.checkedString(description));
        etAPN.setText(Tools.checkedString(apn));
        mLlPicContainer = findViewById(R.id.llPicContainer);
        View inflate = LayoutInflater.from(this).inflate(R.layout.add_pic, null);
        inflate.setOnClickListener(v -> showCameraPop());
        mLlPicContainer.addView(inflate);

//        mRecyclerViewPic = findViewById(R.id.recyclerViewPic);
//        ArrayList<String> list = new ArrayList<>();
//        list.add("");
//
//        mPicAdapter = new PicAdapter(list);
//        mRecyclerViewPic.setAdapter(mPicAdapter);
        llCancel.setOnClickListener(v -> finish());
        llConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String discrepancyTypeId = null;
                for (DictBean bean : mAdapter.getData()) {
                    if (bean.checked) discrepancyTypeId = bean.id;
                }
                if (TextUtils.isEmpty(discrepancyTypeId)) {
                    ToastUtil.showCenterToast("请选择差异类型");
                    return;
                }
                boolean flag = false;
                for (DictBean bean : mAdapter1.getData()) {
                    if (bean.checked) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    ToastUtil.showCenterToast("请选择差异描述");
                    return;
                }
                if (mLoadingDialog != null) {
                    mLoadingDialog = new LoadingDialog(EngTreatmentEditActivity.this);
                }
                if (!mLoadingDialog.isShowing()) {
                    mLoadingDialog.show();
                }
                String description = etDescription.getText().toString().trim();
                String sn = etSN.getText().toString().trim();
                String pn = etPN.getText().toString().trim();
                String apn = etAPN.getText().toString().trim();
                String problemDescription = etDes.getText().toString().trim();
                String jsonData = JsonPostUtil.buildEngJson(mBillId, mStepId, discrepancyTypeId, description, pn, apn, sn, problemDescription, "", mAdapter1.getData());
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonData);
                StaticPresenter.addEngineerDisposition(requestBody, new CallBack<Object>() {
                    @Override
                    public void onCompleted(Object o) {
                        if (mLoadingDialog != null && mLoadingDialog.isShowing())
                            mLoadingDialog.dismiss();
                        ToastUtil.showCenterToast("操作成功");
                        finish();
                    }

                    @Override
                    public void onError() {
                        if (mLoadingDialog != null && mLoadingDialog.isShowing())
                            mLoadingDialog.dismiss();
                        ToastUtil.showCenterToast("操作失败");
                    }
                });
            }
        });
    }

    @Override
    protected void upLoadCompressedImg(File file, String base64, String picturePath) {

    }

    @Override
    protected void showCompressedPic(Bitmap bitmap, String picturePath) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Tools.dp2px(80), Tools.dp2px(80));
        ImageView imageView = new ImageView(this);
        layoutParams.leftMargin = Tools.dp2px(5);
        layoutParams.rightMargin = Tools.dp2px(5);
        imageView.setLayoutParams(layoutParams);
        imageView.setImageBitmap(bitmap);
//        picList.add(bitmap);
        int childCount = mLlPicContainer.getChildCount();
//        imageView.setOnClickListener(v -> showBigPic());
        mLlPicContainer.addView(imageView, childCount - 1);
        if (mLlPicContainer.getChildCount() == 9) {
            mLlPicContainer.removeViewAt(8);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CAMERA_IMAGE || requestCode == RESULT_LOAD_IMAGE)
            if (urls.size() != 0) {
                LoadingDialog dialog = new LoadingDialog(EngTreatmentEditActivity.this, "图片处理中");
                dialog.show();
                String userId = SPUtil.getString(SPKey.Account.USER_ID);
                new Model<ResponseInfo<PicResult>>() {
                    @Override
                    protected void onCompressFinished() {
                        dialog.setMsg("正在上传");
                    }

                    @Override
                    protected void onCompleted() {
                        dialog.dismiss();
                        ToastUtil.showCenterToast("上传成功");
                        urls.clear();
                        EventBus.getDefault().post(new CameraEvent());
                    }

                    @Override
                    protected void onError(Throwable e) {
                        urls.clear();//上传失败也要清除保存的图片本地路径，避免与下次选择的图片混在一起
                    }

                    @Override
                    protected void onNext(ResponseInfo<ResponseInfo<PicResult>> responseInfoResponseInfo) {

                    }

                    @Override
                    protected Observable<ResponseInfo<ResponseInfo<PicResult>>> getObservable(String url, String base64) {
                        return NetManager.getResponseInfoAPI().uploadFile(userId, mPwoNo, mStepId, url, base64);
                    }
                }.upLoadAllCompressedImg();
            }
    }


    private void initEngData(TypeAdapter adapter, int code) {
//        if (mLoadingDialog != null)
//            mLoadingDialog = new LoadingDialog(this);
//        if (!mLoadingDialog.isShowing())
//            mLoadingDialog.show();
        String text = code == 0 ? "DiscrepancyType" : "DiscrepancyDescription";
        String userId = SPUtil.getString(SPKey.Account.USER_ID);
        StaticPresenter.getDictByIdOrCode(userId, null, text, 1, 100, new CallBack<List<DictBean>>() {
            @Override
            public void onCompleted(List<DictBean> dictBeans) {
//                if (mLoadingDialog != null && mLoadingDialog.isShowing()) mLoadingDialog.dismiss();
                adapter.setNewData(dictBeans);
            }

            @Override
            public void onError() {
//                if (mLoadingDialog != null && mLoadingDialog.isShowing()) mLoadingDialog.dismiss();
            }
        });
    }

//    private class PicAdapter extends RecyclerView.Adapter {
//
//        private ArrayList<String> mPicList;
//
//        public PicAdapter(ArrayList<String> picList) {
//            mPicList = picList;
//        }
//
//        @NonNull
//        @Override
//        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
//            return new RecyclerView.ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_item_sub_data, viewGroup, false)) {
//            };
//        }
//
//        @Override
//        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
//            SimpleDraweeView sdv = viewHolder.itemView.findViewById(R.id.sdv);
//            RelativeLayout rl = viewHolder.itemView.findViewById(R.id.rl);
//            sdv.setImageURI(API.BASE_URL + mPicList.get(i));
//            final int position = i;
//            if (position == mPicList.size() - 1) {
//                rl.removeAllViews();
//                rl.addView(LayoutInflater.from(EngTreatmentEditActivity.this).inflate(R.layout.add_pic, null));
//            } else
//                sdv.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        showBigPic(mPicList, position);
//                    }
//                });
//        }
//
//        @Override
//        public int getItemCount() {
//            return mPicList == null ? 0 : mPicList.size();
//        }
//    }

    public void showBigPic(ArrayList<String> data, int position) {
        Intent intent = new Intent(this, BigPicActivity.class);
        intent.putExtra("list", data);
        intent.putExtra("position", position);
        startActivity(intent);
    }
}
